package com.itbaizhan.shopping_user_customer_api.controller;

import com.itbaizhan.shopping_common.pojo.ShoppingUser;
import com.itbaizhan.shopping_common.result.BaseResult;
import com.itbaizhan.shopping_common.service.MessageService;
import com.itbaizhan.shopping_common.service.UserService;
import com.itbaizhan.shopping_common.util.RandomCode;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/user/shoppingUser")
public class ShoppingUserController {
    @DubboReference
    private UserService userService;
    @DubboReference
    private MessageService messageService;

    @GetMapping("/sendMessage")
    public BaseResult sendMessage(String phone) throws ExecutionException, InterruptedException {
        //生成四位随机数
        String code = RandomCode.getCode(4);
        BaseResult result = messageService.sendMessage(phone, code);
        if(result.getCode() == 200) {
            userService.saveRegisterCheckCode(phone,code);
        }
        return result;
    }

    @GetMapping("/registerCheckCode")
    public BaseResult registerCheckCode(String phone,String checkCode) {
        userService.checkRegisterCheckCode(phone,checkCode);
        return BaseResult.ok();
    }

    @PostMapping("/register")
    public BaseResult register(@RequestBody ShoppingUser shoppingUser) {
        userService.register(shoppingUser);
        return BaseResult.ok();
    }

    @PostMapping("/loginPassword")
    public BaseResult<String> loginPassword(@RequestBody ShoppingUser shoppingUser) {
        String token = userService.loginPassword(shoppingUser.getUsername(), shoppingUser.getPassword());
        return BaseResult.ok(token);
    }

    @GetMapping("/sendLoginCheckCode")
    public BaseResult sendLoginCheckCode(String  phone) throws ExecutionException, InterruptedException {
        userService.checkPhone(phone);
        String code = RandomCode.getCode(4);
        BaseResult result = messageService.sendMessage(phone, code);
        if(result.getCode() == 200) {
            userService.saveLoginCheckCode(phone,code);
        }
        return result;
    }

    @PostMapping("/loginCheckCode")
    public BaseResult loginCheckCode(String phone,String checkCode){
        String token = userService.loginCheckCode(phone, checkCode);
        return BaseResult.ok(token);
    }

    @GetMapping("/getName")
    public BaseResult<String> getName(@RequestHeader("Authorization") String authorization) {
        String token  = authorization.replace("Bearer ","");
        String username = userService.getUsername(token);
        return BaseResult.ok(username);
    }
}
